<template>
  <div class="map-container">
    <h1>导览地图</h1>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-loading :full-screen="false">加载中...</el-loading>
    </div>
    
    <!-- 主体内容区 -->
    <div v-else class="content-wrapper">
      <!-- 左侧地图展示区 -->
      <div class="map-content" v-if="groupedMaps.length > 0">
        <div v-for="branch in groupedMaps" :key="branch.name" class="branch-section" :id="'branch-' + branch.id">
          <h2 class="branch-title">{{ branch.name }}</h2>
          <div v-for="floor in branch.floors" :key="floor.floor" class="floor-section" :id="'floor-' + branch.id + '-' + floor.floor">
            <h3 class="floor-title">{{ floor.floor }}层</h3>
            <div class="map-grid">
              <el-card v-for="map in floor.maps" :key="map.id" class="map-item">
                <div class="map-content">
                  <div class="map-header">
                    <h4>{{ map.name }}</h4>
                    <el-button
                      type="text"
                      class="favorite-btn"
                      @click="toggleFavorite(map.id)"
                    >
                      <el-icon :size="24" :color="isFavorite(map.id) ? '#F56C6C' : '#909399'">
                        <Star :filled="isFavorite(map.id)" />
                      </el-icon>
                    </el-button>
                  </div>
                  <div class="image-wrapper">
                    <el-image 
                      :src="map.imageUrl" 
                      :alt="map.name"
                      fit="contain"
                      :preview-src-list="[map.imageUrl]"
                      :initial-index="0"
                      class="map-image"
                    >
                      <template #placeholder>
                        <div class="image-placeholder">
                          <el-icon><Picture /></el-icon>
                          <span>加载中...</span>
                        </div>
                      </template>
                    </el-image>
                  </div>
                  <div class="map-info">
                    <p class="map-description">{{ map.description }}</p>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </div>
      <el-empty v-else description="暂无地图数据" />

      <!-- 右侧导航锚点 -->
      <div class="navigation-sidebar">
        <div class="anchor-list">
          <div v-for="branch in groupedMaps" :key="branch.id" class="anchor-branch">
            <a 
              :href="'#branch-' + branch.id"
              class="branch-link"
              :class="{ active: activeBranch === branch.id }"
            >
              {{ branch.name }}
            </a>
            <div class="anchor-floors">
              <a 
                v-for="floor in branch.floors" 
                :key="floor.floor"
                :href="'#floor-' + branch.id + '-' + floor.floor"
                class="floor-link"
                :class="{ active: activeFloor === branch.id + '-' + floor.floor }"
              >
                {{ floor.floor }}层
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue'
import { getEnabledMaps } from '@/api/map'
import { ElMessage } from 'element-plus'
import { Picture, Star } from '@element-plus/icons-vue'

const loading = ref(false)
const maps = ref([])
const activeBranch = ref('')
const activeFloor = ref('')

// 将地图数据按分馆和楼层分组
const groupedMaps = computed(() => {
  const branches = {}
  maps.value.forEach(map => {
    if (!branches[map.branchId]) {
      branches[map.branchId] = {
        id: map.branchId,
        name: map.branchName,
        floors: {}
      }
    }
    if (!branches[map.branchId].floors[map.floor]) {
      branches[map.branchId].floors[map.floor] = {
        floor: map.floor,
        maps: []
      }
    }
    branches[map.branchId].floors[map.floor].maps.push(map)
  })
  
  // 转换为数组并排序
  return Object.values(branches).map(branch => ({
    ...branch,
    floors: Object.values(branch.floors).sort((a, b) => 
      parseInt(b.floor) - parseInt(a.floor)
    )
  }))
})

// 获取启用的地图列表
const fetchMaps = async () => {
  loading.value = true
  try {
    const data = await getEnabledMaps()
    maps.value = data
  } catch (error) {
    ElMessage.error('获取地图数据失败')
  } finally {
    loading.value = false
  }
}

// 监听滚动更新当前激活的导航项
const updateActiveAnchor = () => {
  const sections = document.querySelectorAll('.branch-section, .floor-section')
  const scrollPosition = window.scrollY + 100 // 添加偏移量以提前激活

  for (const section of sections) {
    const top = section.offsetTop
    const height = section.offsetHeight

    if (scrollPosition >= top && scrollPosition < top + height) {
      if (section.classList.contains('branch-section')) {
        activeBranch.value = section.id.split('-')[1]
      } else if (section.classList.contains('floor-section')) {
        const [, branchId, floor] = section.id.split('-')
        activeFloor.value = branchId + '-' + floor
      }
      break
    }
  }
}

// 用户收藏的地图ID列表
const favorites = ref([])

// 检查地图是否被收藏
const isFavorite = (mapId) => {
  return favorites.value.includes(mapId)
}

// 切换收藏状态
const toggleFavorite = (mapId) => {
  const index = favorites.value.indexOf(mapId)
  if (index === -1) {
    // 添加收藏
    favorites.value.push(mapId)
    ElMessage.success('已添加到收藏')
  } else {
    // 取消收藏
    favorites.value.splice(index, 1)
    ElMessage.success('已取消收藏')
  }
  // 保存到localStorage，使用用户ID作为key的一部分
  const userId = getUserId()
  localStorage.setItem(`mapFavorites_${userId}`, JSON.stringify(favorites.value))
}

// 从localStorage加载收藏数据
const loadFavorites = () => {
  const userId = getUserId()
  const savedFavorites = localStorage.getItem(`mapFavorites_${userId}`)
  if (savedFavorites) {
    favorites.value = JSON.parse(savedFavorites)
  }
}

// 获取当前用户ID
const getUserId = () => {
  // 从localStorage或vuex/pinia中获取用户信息
  // 这里假设用户信息存储在localStorage的userInfo中
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo)
      return user.userInfo.id || 'anonymous'
    } catch (e) {
      return 'anonymous'
    }
  }
  return 'anonymous' // 未登录用户使用anonymous作为ID
}

onMounted(() => {
  fetchMaps()
  loadFavorites()
  window.addEventListener('scroll', updateActiveAnchor)
})

onBeforeUnmount(() => {
  window.removeEventListener('scroll', updateActiveAnchor)
})
</script>

<style scoped>
.map-container {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.content-wrapper {
  display: flex;
  gap: 24px;
  position: relative;
}

.map-content {
  flex: 1;
  margin-right: 0;
}

.branch-section {
  margin-bottom: 40px;
}

.branch-title {
  font-size: 24px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
}

.floor-section {
  margin-bottom: 30px;
}

.floor-title {
  font-size: 20px;
  margin-bottom: 15px;
  color: #666;
}

.map-grid {
  display: flex;
  flex-direction: column;
  gap: 30px;
  padding: 20px;
}

.map-item {
  width: 100%;
  transition: all 0.3s;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }
}

.map-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.map-header {
  padding: 8px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  h4 {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    margin: 0;
  }
}

.favorite-btn {
  padding: 8px;
  transition: all 0.3s;
  border-radius: 50%;
}

.favorite-btn:hover {
  transform: scale(1.2);
  background-color: rgba(245, 108, 108, 0.1);
}

.image-wrapper {
  width: 100%;
  height: 800px;
  overflow: hidden;
  position: relative;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.map-image {
  width: 100%;
  height: 100%;
  display: block;
  cursor: zoom-in;
}

.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  gap: 8px;
  
  .el-icon {
    font-size: 32px;
  }
}

.map-info {
  padding: 8px 0;
}

.map-description {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
}

.navigation-sidebar {
  position: fixed;
  right: 24px;
  bottom: 24px;
  width: 80px;
  background: #fff;
  padding: 12px 8px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.15);
  max-height: 80vh;
  overflow-y: auto;
  z-index: 1000;
}

.anchor-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.anchor-branch {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.branch-link {
  color: #333;
  text-decoration: none;
  font-weight: bold;
  padding: 6px 8px;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
}

.anchor-floors {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.floor-link {
  color: #666;
  text-decoration: none;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 13px;
  text-align: center;
}

.branch-link.active,
.floor-link.active {
  background-color: #409EFF;
  color: #fff;
}

.branch-link:hover,
.floor-link:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}

.branch-link.active:hover,
.floor-link.active:hover {
  background-color: #409EFF;
  color: #fff;
}

@media screen and (max-width: 1400px) {
  .image-wrapper {
    height: 700px;
  }
}

@media screen and (max-width: 1200px) {
  .map-content {
    margin-right: 0;
  }
  
  .navigation-sidebar {
    display: none;
  }
}

@media screen and (max-width: 768px) {
  .image-wrapper {
    height: 400px;
  }
  
  .map-header h4 {
    font-size: 18px;
  }
  
  .map-description {
    font-size: 14px;
  }
}

.navigation-sidebar::-webkit-scrollbar {
  width: 4px;
}

.navigation-sidebar::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 2px;
}

.navigation-sidebar::-webkit-scrollbar-track {
  background: transparent;
}
</style> 